package com.kaizeli.website.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kaizeli.website.mapper.AcceptanceNodeMapper;
import com.kaizeli.website.pojo.entity.AcceptanceNode;
import com.kaizeli.website.pojo.dto.AcceptanceNodeDTO;
import com.kaizeli.website.response.Result;
import com.kaizeli.website.service.AcceptanceNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 验收节点服务实现类
 */
@Service
public class AcceptanceNodeServiceImpl extends ServiceImpl<AcceptanceNodeMapper, AcceptanceNode> implements AcceptanceNodeService {

    @Autowired
    private AcceptanceNodeMapper acceptanceNodeMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 注入开票服务，在验收完成后自动创建开票单
    @Autowired(required = false)
    private com.kaizeli.website.service.InvoiceService invoiceService;

    @Override
    public Result<List<AcceptanceNodeDTO>> getAcceptanceNodesByProjectId(Long projectId) {
        try {
            List<AcceptanceNodeDTO> acceptanceNodes = acceptanceNodeMapper.selectByProjectId(projectId);
            return Result.success(acceptanceNodes);
        } catch (Exception e) {
            return Result.error(500, "查询验收节点失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<AcceptanceNodeDTO>> getAcceptanceNodesByProjectIdAndStatus(Long projectId, String status) {
        try {
            List<AcceptanceNodeDTO> acceptanceNodes = acceptanceNodeMapper.selectByProjectIdAndStatus(projectId, status);
            return Result.success(acceptanceNodes);
        } catch (Exception e) {
            return Result.error(500, "查询验收节点失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<AcceptanceNode> createAcceptanceNode(AcceptanceNode acceptanceNode) {
        try {
            acceptanceNode.setCreateTime(LocalDateTime.now());
            acceptanceNode.setUpdateTime(LocalDateTime.now());
            acceptanceNode.setStatus("待提交");
            save(acceptanceNode);
            return Result.success(acceptanceNode);
        } catch (Exception e) {
            return Result.error(500, "创建验收节点失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> updateAcceptanceNodeStatus(Long id, String status) {
        try {
            int result = acceptanceNodeMapper.updateStatus(id, status);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error(404, "验收节点不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "更新验收节点状态失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> updateActualAcceptanceDate(Long id, String actualAcceptanceDate) {
        try {
            int result = acceptanceNodeMapper.updateActualAcceptanceDate(id, actualAcceptanceDate);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error(404, "验收节点不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "更新实际验收时间失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> submitAcceptanceNode(Long id) {
        try {
            AcceptanceNode acceptanceNode = getById(id);
            if (acceptanceNode == null) {
                return Result.error(404, "验收节点不存在");
            }
            
            if (!"待提交".equals(acceptanceNode.getStatus())) {
                return Result.error(400, "验收节点状态不正确，无法提交");
            }
            
            acceptanceNode.setStatus("待审核");
            acceptanceNode.setUpdateTime(LocalDateTime.now());
            updateById(acceptanceNode);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "提交验收节点失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> reviewAcceptanceNode(Long id, String status, String remark) {
        try {
            // 查询验收节点的当前状态
            String checkSql = "SELECT id, status FROM acceptance_node WHERE id = ?";
            List<Map<String, Object>> nodes = jdbcTemplate.queryForList(checkSql, id);
            
            if (nodes.isEmpty()) {
                return Result.error(404, "验收节点不存在");
            }
            
            String currentStatus = (String) nodes.get(0).get("status");
            
            if (!"待审核".equals(currentStatus)) {
                return Result.error(400, "验收节点状态不正确，无法审核");
            }
            
            // 更新验收节点的状态
            String updateSql = "UPDATE acceptance_node SET status = ?, update_time = NOW()";
            if (remark != null && !remark.trim().isEmpty()) {
                updateSql += ", remark = ?";
                updateSql += " WHERE id = ?";
                jdbcTemplate.update(updateSql, status, remark, id);
            } else {
                updateSql += " WHERE id = ?";
                jdbcTemplate.update(updateSql, status, id);
            }
            
            // 如果审核通过（状态变为"已验收"），自动创建开票单
            if ("已验收".equals(status)) {
                try {
                    // 根据验收节点创建开票单
                    createInvoiceFromAcceptanceNode(id, null);
                } catch (Exception e) {
                    // 记录日志但不影响验收完成
                    System.err.println("自动创建开票单失败: " + e.getMessage());
                    e.printStackTrace();
                }
            }
            
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "审核验收节点失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> completeAcceptanceNode(Long id) {
        try {
            AcceptanceNode acceptanceNode = getById(id);
            if (acceptanceNode == null) {
                return Result.error(404, "验收节点不存在");
            }
            
            if (!"已验收".equals(acceptanceNode.getStatus())) {
                return Result.error(400, "验收节点状态不正确，无法完成");
            }
            
            acceptanceNode.setStatus("已完成");
            acceptanceNode.setActualAcceptanceDate(java.time.LocalDate.now());
            acceptanceNode.setUpdateTime(LocalDateTime.now());
            updateById(acceptanceNode);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "完成验收节点失败：" + e.getMessage());
        }
    }

    /**
     * 根据验收节点自动创建开票单
     */
    private void createInvoiceFromAcceptanceNode(Long acceptanceNodeId, AcceptanceNode acceptanceNodeParam) {
        try {
            // 查询验收节点信息
            String sql = "SELECT an.id, an.project_id, an.acceptance_period, an.total_amount, an.actual_acceptance_date, " +
                        "p.project_name, p.project_code " +
                        "FROM acceptance_node an " +
                        "JOIN project p ON an.project_id = p.id " +
                        "WHERE an.id = ?";
            
            Map<String, Object> nodeInfo = jdbcTemplate.queryForMap(sql, acceptanceNodeId);
            
            // 查询项目信息
            Long projectId = ((Number) nodeInfo.get("project_id")).longValue();
            String projectName = (String) nodeInfo.get("project_name");
            String projectCode = (String) nodeInfo.get("project_code");
            String acceptancePeriod = (String) nodeInfo.get("acceptance_period");
            java.math.BigDecimal totalAmount = (java.math.BigDecimal) nodeInfo.get("total_amount");
            if (totalAmount == null) {
                totalAmount = java.math.BigDecimal.ZERO;
            }
            
            // 生成开票单编号
            String invoiceNo = "INV" + System.currentTimeMillis();
            
            // 设置开票日期
            java.time.LocalDate invoiceDate = java.time.LocalDate.now();
            if (nodeInfo.get("actual_acceptance_date") != null) {
                invoiceDate = ((java.time.LocalDate) nodeInfo.get("actual_acceptance_date"));
            }
            
            // 备注信息
            String remark = "根据验收节点自动创建";
            if (acceptancePeriod != null) {
                remark = "根据验收节点自动创建，验收周期：" + acceptancePeriod;
            }
            
            // 直接插入开票单
            String insertSql = "INSERT INTO invoice " +
                    "(invoice_no, acceptance_id, project_id, project_name, project_code, " +
                    "invoice_date, invoice_amount, total_amount, invoice_status, " +
                    "invoice_type, tax_rate, tax_amount, remark, create_time, update_time) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, '待开票', '增值税专用发票', 0, 0, ?, NOW(), NOW())";
            
            jdbcTemplate.update(insertSql, 
                    invoiceNo, 
                    acceptanceNodeId.intValue(),
                    projectId,
                    projectName,
                    projectCode,
                    invoiceDate,
                    totalAmount,
                    totalAmount,
                    remark
            );
            
            System.out.println("验收节点审核通过，已自动创建开票单：" + invoiceNo);
        } catch (Exception e) {
            System.err.println("创建开票单失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
